package com.zzedu.web.controller.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzedu.common.annotation.Log;
import com.zzedu.common.core.controller.BaseController;
import com.zzedu.common.core.domain.AjaxResult;
import com.zzedu.common.core.domain.entity.SysDept;
import com.zzedu.common.enums.BusinessType;
import com.zzedu.common.utils.StringUtils;
import com.zzedu.system.service.ISysDeptService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:dept:list')")
    @RequestMapping("/list")
    public AjaxResult list(@RequestBody SysDept dept) {
        IPage<SysDept> depts = deptService.selectDeptList(new Page<>(1L, -1L), dept);
        return success(depts.getRecords());
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        IPage<SysDept> depts = deptService.selectDeptList(new Page<>(1L, -1L), new SysDept());
        depts.getRecords().removeIf(d -> d.getId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts.getRecords());
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:dept:query')")
    @RequestMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId) {
        return success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @RequestMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        SysDept info = deptService.selectDeptById(dept.getParentId());
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return toAjax(deptService.save(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @RequestMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        SysDept newParentDept = deptService.selectDeptById(dept.getParentId());
        SysDept oldDept = deptService.selectDeptById(dept.getId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getId(), newAncestors, oldAncestors);
        }

        return toAjax(deptService.updateById(dept));
    }
    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<SysDept> children = deptService.selectChildrenDeptById(deptId);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            deptService.updateDeptChildren(children);
        }
    }
    /**
     * 删除部门
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @RequestMapping("/remove/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        return toAjax(deptService.removeById(deptId));
    }
}
